package com.renl.juc.lock;

import sun.rmi.runtime.NewThreadAction;

import java.util.concurrent.atomic.AtomicReference;

import static java.lang.Thread.sleep;

/**
 * @author renl
 * @date 2020/1/7
 */
public class SpinLockDemo {
  AtomicReference<Thread> atomicReference = new AtomicReference<>();
  public void mylock(){
    Thread thread = Thread.currentThread();
    System.out.println(Thread.currentThread().getName() + "\t come in");
    while (!atomicReference.compareAndSet(null,thread)){

    }
  }
  public void unLock(){
    Thread thread = Thread.currentThread();
    atomicReference.compareAndSet(thread,null);
    System.out.println(Thread.currentThread().getName() + "\t unlocked");
  }

  public static void main(String[] args) {
    SpinLockDemo spinLockDemo = new SpinLockDemo();
    new Thread(() -> {
      spinLockDemo.mylock();
      try {
        sleep(5);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      spinLockDemo.unLock();
    },"a").start();
    try {
      sleep(1);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    new Thread(() -> {
      spinLockDemo.mylock();
//      try {
//        sleep(1);
//      } catch (InterruptedException e) {
//        e.printStackTrace();
//      }
      spinLockDemo.unLock();
    },"b").start();
  }

}
